import router from "../router";
import { getToken } from "./token";
import { useUserInfoStore } from "../store/userInfo"
import pinia from "../store";


const userInfoStore = useUserInfoStore(pinia)


const whiteList = ['/login','/register','/detail','/searchzyt','/goodslist','/home','/phone','/email','/recommend','/category','/search','/404']

router.beforeEach(async (to,from,next)=>{
  /* 获取token */
  const token = getToken()
  /* 判断token是否存在 */
  if(token){
    /* 获取用户信息 */
    const name = userInfoStore.userInfo.name
    /* 如果存在用户信息,则表示是登录用户,放行 */
    if(name){
      next()
      /* 不存在用户信息,则表示token过期 */
    }else{
      try {
        await userInfoStore.getUserInfo()
        next()
      } catch (error) {
        userInfoStore.resetUserInfo()
        next('/login')
      }
    }
    /* 不存在token */
  }else{
    /* 判断路由是否在白名单列表,存在则放行 */
    if(whiteList.includes(to.path)){
      next()
    }else{
      /* 不存在则去登录页面 */
      next('/login')
    }
  }
})